package day06;

import java.io.RandomAccessFile;
import java.util.Scanner;

/**
 * 要求用户输入一个文件名，并复制当前目录中该文件，并取名为"原文件名_copy.后缀名"
 * 定义两个方法分别使用单字节形式复制，以及字节数组形式复制
 * @author Bonnie
 *
 */
public class Test07 {
	public static void main(String[] args) throws Exception {
		Scanner console = new Scanner(System.in);
		System.out.print("请输入一个文件名：");
		String name = console.next();
		Test07 t = new Test07();
		t.copy1(name);
//		t.copy2(name);
		console.close();
	}
	/**
	 * 使用单字节方式复制
	 * @param name 要复制的文件名
	 * @throws Exception 
	 */
	public void copy1(String name) throws Exception{
		String[] ss = name.split("\\.");
		RandomAccessFile raf = new RandomAccessFile(name, "r");
		RandomAccessFile rafNew = new RandomAccessFile(ss[0] + "_copy." + ss[1], "rw");
		int len = -1;
		while ((len = raf.read()) != -1) {
			rafNew.write(len);
		}
		System.out.println("复制成功！");
		raf.close();
		rafNew.close();
	}
	/**
	 * 使用字节数组形式复制
	 * @param name 要复制的文件名
	 * @throws Exception 
	 */
	public void copy2(String name) throws Exception{
		String[] ss = name.split("\\.");
		RandomAccessFile raf = new RandomAccessFile(name, "r");
		RandomAccessFile rafNew = new RandomAccessFile(ss[0] + "_copy." + ss[1], "rw");
		byte[] bs = new byte[1024 * 1024];
		int len = -1;
		while ((len = raf.read(bs)) != -1) {
			rafNew.write(bs, 0, len);
//			String str = new String(bs, 0, len);
//			System.out.println(str);
		}
		System.out.println("复制成功！");
		raf.close();
		rafNew.close();
	}
}
